package com.tangcco.lockwell.controller.student;

import cn.hutool.core.date.DateUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.tangcco.lockwell.base.BaseApiController;
import com.tangcco.lockwell.base.RestResponse;
import com.tangcco.lockwell.domain.RegisterPhoneValidateCode;
import com.tangcco.lockwell.domain.User;
import com.tangcco.lockwell.domain.UserEventLog;
import com.tangcco.lockwell.domain.enums.RoleEnum;
import com.tangcco.lockwell.domain.enums.UserStatusEnum;
import com.tangcco.lockwell.event.UserEvent;
import com.tangcco.lockwell.service.AuthenticationService;
import com.tangcco.lockwell.service.RegisterPhoneValidateService;
import com.tangcco.lockwell.service.UserEventLogService;
import com.tangcco.lockwell.service.UserService;
import com.tangcco.lockwell.utility.DateTimeUtil;
import com.tangcco.lockwell.utility.StudentSubjectUtil;
import com.tangcco.lockwell.viewmodel.student.user.UserRegisterVM;
import com.tangcco.lockwell.viewmodel.student.user.UserRestPasswordVM;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

import static com.tangcco.lockwell.utility.DateToString.dateToString;

/**
 * 学生端用户信息
 *
 * @author yanxinping
 * @date 2025-01-09 14:32
 */
@RestController
@Slf4j
@RequestMapping("/api/student/user")
public class UserController extends BaseApiController {
    @Resource
    UserService userService;
    @Resource
    UserEventLogService userEventLogService;
    @Resource
    AuthenticationService authenticationService;
    @Resource
    ApplicationEventPublisher eventPublisher;
    @Resource
    RegisterPhoneValidateService registerPhoneValidateService;
    @Resource
    StudentSubjectUtil studentSubjectUtil;
    @Resource
    Client smsClient;


    @RequestMapping(value = "/edit")
    public RestResponse<User> edit(@RequestBody @Valid User model) {

        if (model.getUserId() == null) {

            model.setDeleted(0);
            model.setIntegral(1000);
            model.setCreateTime(dateToString(new Date()));
            userService.insert(model);
        } else {
            model.setModifyTime(dateToString(new Date()));
            userService.updateByIdFilter(model);
        }
        return RestResponse.ok();
    }
    @RequestMapping(value = "/editAfterRegister")
    public RestResponse<User> editAfterRegister(@RequestBody @Valid User model) {
        //注册后的五分钟允许修改
        User existUser = userService.getUserById(model.getUserId());
        if (existUser==null || existUser.getCreateTime() == null ) {
            return new RestResponse<>(-1, "用户不存在");
        }
        // 给定的时间
        LocalDateTime givenTime = convertToLocalDateTime(DateTimeUtil.parse(existUser.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        // 当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        if(!isWithinFiveMinute(givenTime, currentTime)){
            return new RestResponse<>(-1, "注册后五分钟后不允许修改");

        }
        model.setModifyTime(dateToString(new Date()));
        userService.updateByIdFilter(model);
        return RestResponse.ok();
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public RestResponse register(@RequestBody @Valid UserRegisterVM model) {
        User existUser = userService.getUserByUserName(model.getUserName());
        if (null != existUser) {
            return new RestResponse<>(2, "用户已存在");
        }
        User exstPhone = userService.getUserByPhone(model.getPhone());
        if (null != exstPhone) {
            return new RestResponse<>(3, "手机号已存在");
        }
        RegisterPhoneValidateCode validateCode = registerPhoneValidateService.selectByPhoneAndSendType(model.getPhone(),model.getSendType());
        if (validateCode == null) {
            return new RestResponse<>(4, "验证码不存在");
        }
        if(!validateCode.getValidCode().equals(model.getValidCode())){
            return new RestResponse<>(5, "验证码错误");
        }
        // 给定的时间
        LocalDateTime givenTime = convertToLocalDateTime(validateCode.getCreateTime());
        // 当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        if(!isWithinOneMinute(givenTime, currentTime)){
            return new RestResponse<>(6, "验证码已过期");
        }
        User user = modelMapper.map(model, User.class);
        String encodePwd = authenticationService.pwdEncode(model.getPassword());
        user.setUserUuid(UUID.randomUUID().toString());
        user.setPassword(encodePwd);
        user.setRole(RoleEnum.STUDENT.getCode());
        user.setStatus(UserStatusEnum.Enable.getCode());
        user.setLastActiveTime(DateTimeUtil.dateFormat(new Date()));
        user.setCreateTime(DateTimeUtil.dateFormat(new Date()));
        user.setDeleted(0);
        user.setOptSubject(studentSubjectUtil.getDefaultSubjectId());
        userService.insertByFilter(user);
        UserEventLog userEventLog = new UserEventLog(user.getUserId(), user.getUserName(), user.getRealName(), DateTimeUtil.dateFormat(new Date()));
        userEventLog.setContent("欢迎 " + user.getUserName() + " 注册来到乐考无忧ai提分系统");
        eventPublisher.publishEvent(new UserEvent(userEventLog));
        return RestResponse.ok(user.getUserId());
    }
    //忘记密码修改密码操作
    @RequestMapping(value = "/register/resetPassword", method = RequestMethod.POST)
    public RestResponse resetPassword(@RequestBody UserRestPasswordVM model) {
        User existUser = userService.getUserByPhone(model.getPhone());
        if (null == existUser) {
            return new RestResponse<>(2, "用户不存在");
        }
        //校验验证码
        RegisterPhoneValidateCode validateCode = registerPhoneValidateService.selectByPhoneAndSendType(model.getPhone(),model.getSendType());
        if (validateCode == null) {
            return new RestResponse<>(4, "验证码不存在");
        }
        if(!validateCode.getValidCode().equals(model.getVerificationCode())){
            return new RestResponse<>(5, "验证码错误");
        }
        // 给定的时间
        LocalDateTime givenTime = convertToLocalDateTime(validateCode.getCreateTime());
        // 当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        if(!isWithinOneMinute(givenTime, currentTime)){
            return new RestResponse<>(6, "验证码已过期");
        }
        String encodePwd = authenticationService.pwdEncode(model.getNewPassword());
        existUser.setPassword(encodePwd);
        userService.updateByIdFilter(existUser);
        return RestResponse.ok();
    }

    @RequestMapping(value = "/sendSmsCode",method = RequestMethod.POST)
    public RestResponse sendSmsCode(@RequestBody UserRegisterVM model) {
        // 验证手机号是否合法
        if (!isValidPhoneNumber(model.getPhone())) {
            return new RestResponse<>(7, "手机号格式不正确");
        }
        String code = generateSmsCode();
        String templateCode = "";
        if(model.getSendType()==1){
            templateCode = "SMS_476465120";
        }else if(model.getSendType()==2){
            templateCode = "SMS_476465120";
        }else if(model.getSendType()==3){
            templateCode = "SMS_476465120";
        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(model.getPhone())
                .setSignName("乐考无忧")
                .setTemplateCode(templateCode)
                .setTemplateParam("{\"code\":\"" + code + "\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SendSmsResponse resp = smsClient.sendSmsWithOptions(sendSmsRequest, runtime);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp));
            if(resp.getBody() != null && "OK".equals(resp.getBody().getCode())){
                //验证码保存到数据库
                RegisterPhoneValidateCode validateCode = new RegisterPhoneValidateCode();
                validateCode.setPhone(model.getPhone());
                validateCode.setValidCode(code);
                validateCode.setCreateTime(new Date());
                validateCode.setSendType(model.getSendType());
                registerPhoneValidateService.insertSelective(validateCode);
            }
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return RestResponse.ok();
    }
    // 验证手机号是否合法
    private boolean isValidPhoneNumber(String phoneNumber) {
        // 定义手机号的正则表达式模式
        String regex = "^1[3-9]\\d{9}$";
        return phoneNumber.matches(regex);
    }
    // 生成随机的短信验证码
    private String generateSmsCode() {
        // 生成 6 位随机数字验证码
        int code = (int) (Math.random() * 1000000);
        return String.format("%06d", code);
    }

    public static boolean isWithinOneMinute(LocalDateTime time1, LocalDateTime time2) {
        Duration duration = Duration.between(time1, time2).abs();
        return duration.getSeconds() <= 60;
    }
    public static boolean isWithinFiveMinute(LocalDateTime time1, LocalDateTime time2) {
        Duration duration = Duration.between(time1, time2).abs();
        return duration.getSeconds() <= 300;
    }
    public static LocalDateTime convertToLocalDateTime(Date date) {
        // 获取 Date 对象的时间戳
        Instant instant = date.toInstant();
        // 使用系统默认的时区将 Instant 转换为 LocalDateTime
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }
}